package perform.utilities;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.sql.ResultSet;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Date;
import perform.mappings.ClassMappings;
import perform.type.Type;

public class ValueParser {
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public Object parseValue(Class<?> dataType,
			String columnLabel, ResultSet rs) throws Exception {
		if(Type.class.isAssignableFrom(dataType)){
			Type type = (Type) dataType.newInstance();
			Field field = ClassMappings.getIDField(type.getClass());
			field.set(type, parseValue(field.getType(), columnLabel, rs));
			return type;
		} else if(dataType.equals(int.class) || dataType.equals(Integer.class)){
			return rs.getInt(columnLabel);
		} else if(dataType.equals(String.class)){
			return rs.getString(columnLabel);
		} else if(dataType.equals(long.class) || dataType.equals(Long.class)){
			return rs.getLong(columnLabel);
		} else if(dataType.equals(short.class) || dataType.equals(Short.class)){
			return rs.getShort(columnLabel);
		} else if(dataType.equals(float.class) || dataType.equals(Float.class)){
			return rs.getFloat(columnLabel);
		} else if(dataType.equals(Double.class) || dataType.equals(double.class)){
			return rs.getDouble(columnLabel);
		} else if(dataType.equals(BigDecimal.class)){
			return rs.getBigDecimal(columnLabel);
		} else if(dataType.equals(byte.class) || dataType.equals(Byte.class)){
			return rs.getByte(columnLabel);
		} else if(dataType.equals(boolean.class) || dataType.equals(Boolean.class)){
			return rs.getBoolean(columnLabel);
		} else if(dataType.equals(byte[].class)){
			return rs.getBytes(columnLabel);
		} else if(dataType.equals(Date.class)){
			return new Date(rs.getDate(columnLabel).getTime());
		} else if(dataType.isEnum()){
			return Enum.valueOf((Class<? extends Enum>) dataType, rs.getString(columnLabel));
		} else if(dataType.equals(char[].class) || dataType.equals(Character[].class)){
			return rs.getString(columnLabel).toCharArray();
		} else if(dataType.equals(CharSequence.class)){
			String result = rs.getString(columnLabel);
			return result.subSequence(0, result.length());
		} else if(dataType.equals(Character.class) || dataType.equals(char.class)){
			return rs.getString(columnLabel).charAt(0);
		} else if(dataType.equals(java.sql.Date.class)){
			return rs.getDate(columnLabel);
		} else if(dataType.equals(Calendar.class)){
			Calendar calendar = Calendar.getInstance();
			calendar.setTimeInMillis(rs.getDate(columnLabel).getTime());
			return calendar;
		} else if(dataType.equals(Time.class)){
			return rs.getTime(columnLabel);
		} else if(dataType.equals(Timestamp.class)){
			return rs.getTimestamp(columnLabel);
		} else {
			return rs.getObject(columnLabel);
		}
	}

}
